<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 2021/3/31
 * Time: 9:39
 */

namespace common\wodrow\wyiibackup;


use common\components\Tools;
use creocoder\flysystem\Filesystem;
use yii\base\Component;

/**
 * Class FileJobBackup
 * @package common\wodrow\wyiibackup
 */
class FileJobBackup extends Component
{
    public $name;
    public $from;
    public $to;
    public $isShowExecLog = 1;
    public $showEnd = "done!";
    public $logFile = "execLogs-".YII_BT_DATETIME1;

    /**
     * @var Filesystem $master
     */
    public $master;

    /**
     * @var Filesystem $slave
     */
    public $slave;

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        $this->master = \Yii::createObject($this->from);
        $this->slave = \Yii::createObject($this->to);
    }

    /**
     * 备份文件
     * @param Filesystem $master
     * @param Filesystem $slave
     * @param string $log_name_pre
     */
    public function fileSysBackup()
    {
        $master = $this->master;
        $slave = $this->slave;
        $slc = $master->listContents('', true);
        $log = [
            'has' => [],
            'update' => [],
            'sizeError' => [],
            'done' => [],
        ];
        foreach ($slc as $k => $v){
            $type = $v['type'];
            $fromPath = $v['path'];
            $toPath = $this->name. DIRECTORY_SEPARATOR .$v['path'];
            if ($this->isShowExecLog)var_dump($fromPath);
            if ($type != 'dir'){
                if ($slave->has($toPath)){
                    if ($slave->getSize($toPath) < $master->getSize($fromPath)){
                        $c = $master->readStream($fromPath);
                        $slave->updateStream($toPath, $c);
                        $log['update'][] = $fromPath;
                        if ($this->isShowExecLog)var_dump("update");
                    }elseif ($slave->getSize($toPath) == $master->getSize($fromPath)){
                        $log['has'][] = $fromPath;
                        if ($this->isShowExecLog)var_dump("has");
                    }else{
                        $log['sizeError'][] = $fromPath;
                        if ($this->isShowExecLog)var_dump("size error");
                    }
                }else{
                    $c = $master->readStream($fromPath);
                    $slave->writeStream($toPath, $c);
                    $log['done'][] = $fromPath;
                    if ($this->isShowExecLog)var_dump("write");
                }
            }
        }
        if ($this->logFile){
            Tools::yiiLog($log, $this->name . "-" . $this->logFile);
        }
        var_dump($this->showEnd);
    }
}